package com.dapeis.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.fusesource.mqtt.codec.SUBACK;
import org.springframework.stereotype.Service;

import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.dao.DBService;
import com.ag.dao.IDao;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.dao.IStylistCityMapper;
import com.dapeis.domain.StylistCity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Service
public class StylistCityService extends DBService<StylistCity> {

    @Resource
    IStylistCityMapper mapper;

    @Override
    protected IDao<StylistCity> getIDao() {
	return mapper;
    }

    /**
     * 获取省_市_区Code
     * 
     * @param code
     * @return
     */
    public Map getProvince_City_CountyCode(String code) {
	Map<String, String> hasMap = new HashMap<String,String>();
	StylistCity countyCity = getCity(code);
	if(null!= countyCity && countyCity.getLevelType().equals("3")){
	    hasMap.put("countyCode", countyCity.getID().toString());
	    StylistCity cCity = getCity(countyCity.getParentId().toString());
	    if(null!=cCity && cCity.getLevelType().equals("2")){
		hasMap.put("cityCode", cCity.getID().toString());
		StylistCity proCity = getCity(cCity.getParentId());
		if(null != proCity && proCity.getLevelType().equals("1")){
		    hasMap.put("provinceCode", proCity.getID().toString());
		}
	    }
	}
	return hasMap;
    }
    
    
    public StylistCity getCity(String code) {
	StylistCity city = mapper.selectByPrimaryKey(new Integer(code)
		.intValue());
	return city;
    }

    public String getDataFullName(String code) {
	StylistCity city = getCity(code);
	AgAssert.notNull(city, SysTipsException.class, "错误的城市Code:" + code);
	StringBuffer sbufBuffer = new StringBuffer();
	if (city.getLevelType().equals("1")) {
	    // 省
	    sbufBuffer.append(city.getName());
	}
	if (city.getLevelType().equals("2")) {
	    // 市
	    StylistCity provCity = mapper.selectByPrimaryKey(new Integer(city
		    .getParentId()));
	    if (null != provCity) {
		sbufBuffer.append(provCity.getName());
	    }
	    sbufBuffer.append(city.getName());
	}
	if (city.getLevelType().equals("3")) {
	    // 区县
	    StylistCity cCity = mapper.selectByPrimaryKey(new Integer(city
		    .getParentId()));
	    if (cCity != null) {
		StylistCity _tempProv = mapper.selectByPrimaryKey(new Integer(
			cCity.getParentId()));
		if (null != _tempProv) {
		    sbufBuffer.append(_tempProv.getName())
			    .append(cCity.getName()).append(city.getName());
		}
	    }
	}

	return sbufBuffer.toString();
    }

    @Override
    public List<StylistCity> select(StylistCity record) {
	// TODO Auto-generated method stub
	return super.select(record);
    }

    public JsonArray writeCityData(HttpServletRequest request) {
	List<StylistCity> allDBData = selectAll();
	List<StylistCity> provinceList = new ArrayList<StylistCity>();
	List<StylistCity> cityList = new ArrayList<StylistCity>();
	List<StylistCity> countyList = new ArrayList<StylistCity>();

	for (Iterator iter = allDBData.iterator(); iter.hasNext();) {
	    StylistCity _city = (StylistCity) iter.next();
	    if (_city.getLevelType().equals("1"))
		provinceList.add(_city);
	    if (_city.getLevelType().equals("2"))
		cityList.add(_city);
	    if (_city.getLevelType().equals("3"))
		countyList.add(_city);
	    // System.out.println("数据错误:" + _city.getName());
	}
	JsonArray rootJsonArray = new JsonArray();
	// JsonArray cityJsonArray = new JsonArray();
	// JsonArray countryJsonArray = new JsonArray();
	for (Iterator proIterator = provinceList.iterator(); proIterator
		.hasNext();) {
	    StylistCity pCity = (StylistCity) proIterator.next();
	    if (null == pCity)
		continue;
	    JsonObject pJson = new JsonObject();
	    pJson.addProperty("name", pCity.getName());
	    pJson.addProperty("code", pCity.getID());
	    JsonArray cityJsonArray = new JsonArray();

	    for (Iterator cityIterator = cityList.iterator(); cityIterator
		    .hasNext();) {
		StylistCity cCity = (StylistCity) cityIterator.next();
		if (pCity.getID().equals(cCity.getParentId())) {
		    //
		    JsonObject cityJson = new JsonObject();
		    cityJson.addProperty("name", cCity.getName());
		    cityJson.addProperty("code", cCity.getID());
		    cityJsonArray.add(cityJson);
		    JsonArray countryJsonArray = new JsonArray();
		    for (Iterator countryIterator = countyList.iterator(); countryIterator
			    .hasNext();) {

			StylistCity counCity = (StylistCity) countryIterator
				.next();
			if (cCity.getID().equals(counCity.getParentId())) {
			    JsonObject countyJson = new JsonObject();
			    countyJson.addProperty("name", counCity.getName());
			    countyJson.addProperty("code", counCity.getID());
			    countryJsonArray.add(countyJson);
			}

		    }
		    cityJson.add("sub",
			    AGsonBuilder.create().toJsonTree(countryJsonArray));
		}

	    }
	    pJson.add("sub", AGsonBuilder.create().toJsonTree(cityJsonArray));
	    rootJsonArray.add(pJson);
	}

	return rootJsonArray;

	/*
	 * String filePath = FileUtils.splicePaths(request.getRealPath(""),
	 * "resources/js/city_app.js"); File file = new File(filePath); if
	 * (!file.exists()) { file.getParentFile().mkdirs(); try {
	 * file.createNewFile();
	 * 
	 * 
	 * 
	 * } catch (IOException e) { e.printStackTrace(); } }
	 */
	/*
	 * response.setContentType(MediaType.APPLICATION_JSON_VALUE +
	 * ";charset=UTF-8"); Writer out = new BufferedWriter(new
	 * OutputStreamWriter( new FileOutputStream(file), "UTF-8"));
	 * PrintWriter writer = new PrintWriter(out);
	 * writer.write("COUNTRY_STATIC_JSON = " +
	 * provinceService.countrys.toString()); writer.flush(); writer.close();
	 * 
	 * JsonObject jsonObject = new JsonObject();
	 * jsonObject.addProperty("succ", "同步成功！"); return jsonObject;
	 */

    }
}
